<template>
  <div>
    <div
      id="cardRoot"
      class="flex items-center justify-center h-full"
      ref="cardRoot"
      style="min-height: 86vh; user-select: none"
      @wheel.prevent="handleMouseWheel"
      @mousedown.prevent="handleMouseDown"
      @mousemove.prevent="handleMouseMove"
      @mouseup.prevent="handleMouseUp"
      @mouseleave.prevent="handleMouseUp"
      :style="{
        transform: `scale(${pageScale}) translate(${moveX}px,${moveY}px)`,
        cursor: lastPosition ? 'move' : 'unset',
      }"
      v-if="isPageShow"
    >
      <card-root ref="cardRootModule" :isShare="isShare" @pageInit="pageInit" />
    </div>
    <!-- 按钮 -->
    <div class="fixed bg-white top-128 right-16" v-if="!isShare">
      <div class="flex">
        <!-- <c-button
          label="分享"
          icon="icon_share"
          @click.native="handleShare"
        ></c-button> -->
        <c-button
          :label="$i18n.t('mind.dataDemonstration')"
          icon="icon_btn_demo"
          @click.native="handleDataDemonstration"
          class="ml-8"
        ></c-button>
        <c-button
          :label="exportPdfLoading ? '导出中...' : '导出PDF'"
          icon="icon_btn_export_3d82ea"
          :loading="exportPdfLoading"
          @click.native="handleExportPdf"
          class="ml-8"
        ></c-button>
      </div>
    </div>
    <!-- 分享 -->
    <Share :open.sync="open" :paramsData="paramsData" listParams="type" />
    <!-- 分享提取码 -->
    <el-dialog
      :visible.sync="shareNoticeShow"
      :show-close="false"
      class="share-code-dialog"
      :width="screenWidth"
      :title="$i18n.t('mind.extractionCode')"
      append-to-body
      :close-on-click-modal="false"
    >
      <template #title>
        <div class="flex items-center">
          <!-- <svg-icon icon-class="logo_haiyun" class-name="text-48" /> -->
          <strong class="ml-16 color-FFFFFF">{{ $i18n.t("mind.haiyunZhizhiPageSharing") }}</strong>
        </div>
      </template>
      <div class="flex flex-col items-center justify-center">
        <div class="w-full color-333333">{{ $i18n.t("mind.pleaseEnterTheViewingCode") }}</div>
        <div class="flex mt-16">
          <el-input
            v-model="shareCode"
            :placeholder="$i18n.t('mind.pleaseEnterTheViewingCode')"
            class="flex-1"
            @keyup.enter.native="handleCodeInput"
          />
          <el-button
            class="ml-16"
            type="primary"
            :loading="loading"
            @click="handleCodeInput"
            >{{ $i18n.t("mind.confirmTheView") }}</el-button
          >
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSharingPageValidType, getSharingPage ,queryNodeInfo,queryNextNodes,listByBarcodeOrSns} from "@/api/tool/share";
import CardRoot from "@/views/mind/components/card-root.vue";
import CButton from "./components/common/CButton.vue";
import Share from "./components/share/index.vue";
import DrawLine from "./script/draw-line.js";
import { getPdf } from "@/utils/exportPdf";
import moment from "moment";

const SCALE_MAX = 1.2; //缩放倍数上限
const SCALE_MIN = 0.5; //缩放倍数下限
const SCALE_STEP = 0.01; //缩放增幅

export default {
  name: "mind",
  components: { CardRoot, CButton, Share },
  mixins: [DrawLine],
  data() {
    return {
      pageScale: 1,
      lastPosition: null,
      moveX: 0,
      moveY: 0,
      basePosition: { x: 0, y: 0 }, //每次拖拽后记录下位置
      exportPdfLoading: false, // 导出PDF
      isShare: false, // 是否为分享页面
      open: false,
      paramsData: {},
      isPageShow: false,
      // 分享提取码
      loading: false,
      shareNoticeShow: false,
      shareCode: "",
      shareUUid: "",
      timerout: null,
    };
  },
  computed: {
    screenWidth() {
      return Math.min(window.innerWidth, 550) + "px";
    },
  },
  watch: {
    "$store.state.mind.nodeCards": {
      handler(val) {
        val && this.initDraw();
      },
      deep: true,
    },
  },
  created() {
    this.shareInit();
  },
  beforeDestroy() {
    clearTimeout(this.timerout);
  },
  methods: {
    handleMouseWheel(e) {
      const { wheelDelta } = e;
      if (wheelDelta > 0) {
        this.pageScale <= SCALE_MAX && (this.pageScale += SCALE_STEP);
      } else {
        this.pageScale >= SCALE_MIN && (this.pageScale -= SCALE_STEP);
      }
    },
    handleMouseDown(e) {
      const { clientX: x, clientY: y } = e;
      this.lastPosition = { x, y };
    },
    handleMouseMove(e) {
      if (this.lastPosition) {
        const { clientX, clientY } = e;
        // 每次移动的距离=上次结束的坐标+本次移动的偏移量*缩放的倍数(缩小移动距离增大,放大移动距离减小)
        this.moveX =
          this.basePosition.x +
          (clientX - this.lastPosition.x) *
            (SCALE_MAX + SCALE_MAX - this.pageScale);
        this.moveY =
          this.basePosition.y +
          (clientY - this.lastPosition.y) *
            (SCALE_MAX + SCALE_MAX - this.pageScale);
      }
    },
    handleMouseUp(e) {
      this.basePosition = { x: this.moveX, y: this.moveY };
      this.lastPosition = null;
    },
    // 页面初始化
    pageInit() {
      this.pageScale = 1;
      this.lastPosition = null;
      this.moveX = 0;
      this.moveY = 0;
      this.basePosition = { x: 0, y: 0 };
    },
    // 数据演示
    handleDataDemonstration() {
      this.$refs.cardRootModule.dataDemonstration();
    },
    // 导出PDF
    handleExportPdf() {
      if (this.exportPdfLoading) {
        return;
      }
      this.exportPdfLoading = true;
      this.timerout = setTimeout(() => {
        getPdf(
          `条码追溯${moment().format("YYYY_MM_DD_HH_mm_ss")}`,
          "cardRoot",
          this.pageScale
        ).then(() => {
          this.exportPdfLoading = false;
        });
      }, 1000);
    },
    // 分享
    handleCodeInput() {
      if (!this.shareCode) {
        this.$message.error($i18n.t("mind.pleaseEnterTheViewingCode"))
        return;
      }
      this.getShareData(this.shareUUid, this.shareCode);
    },
    handleShare() {
      const { codeType, maiInput, isDataDemonstration } =
        this.$refs.cardRootModule;
      this.paramsData = {
        type: codeType === "1" ? "by_bar_code" : "by_batch",
        typeName: codeType === "1" ? $i18n.t('mind.byBarcode') : $i18n.t('mind.byBatch'),
        pageContent: $i18n.t('mind.materialTraceabilitySharing'),
        orderNo:
          maiInput && this.$store.state.mind.nodeCards.length > 1
            ? isDataDemonstration
              ? `${maiInput}!##isDataDemonstration`
              : maiInput
            : "",
      };
      this.open = true;
    },
    shareInit() {
      const { path, query } = this.$route;
      const { uuid, extractedCode } = query;
      if (path === "/mind/share") {
        this.isShare = true;
        this.isPageShow = false;
        getSharingPageValidType(uuid).then((res) => {
          if (!res.data.result) {
            this.isPageShow = false;
            // this.msgError("分享链接地址有误");
            this.$message.error($i18n.t("mind.msg1"))
            return;
          }
          const { validType } = res.data.result;
          if (validType === "1") {
            if (!extractedCode) {
              this.shareNoticeShow = true;
              this.shareUUid = uuid;
              return;
            }
          }
          this.getShareData(uuid, extractedCode);
        });
      } else {
        this.isShare = false;
        this.isPageShow = true;
      }
    },
    getShareData(uuid, extractedCode) {
      this.loading = true;
      getSharingPage({ uuid, extractedCode })
        .then((res) => {
            const { result } = res.data;
            if (!result) {
              this.$message.error($i18n.t("mind.msg1"))
              return;
            }
            const { orderNo, type, pageContent } = result;
            const orderNoInit = orderNo.split("!##");
            let businessCode = "";
            if (orderNoInit.length === 1) {
              businessCode = orderNo;
            } else {
              businessCode = orderNoInit[0];
            }
            const codeType = type === "by_bar_code" ? "1" : "2";
            this.shareNoticeShow = false;
            this.isPageShow = true;
            this.$store.dispatch(
              "mind/saveDataOrigin",
              JSON.parse(pageContent)
            );
            this.$nextTick(() => {
              this.$refs.cardRootModule.codeType = codeType;
              this.$store.state.mind.codeType = codeType;
              this.$refs.cardRootModule.maiInput = businessCode;
              // 数据演示分享
              if (
                orderNoInit.length > 1 &&
                orderNoInit[1] === "isDataDemonstration"
              ) {
                this.$refs.cardRootModule.dataDemonstration();
                return;
              }
              this.$refs.cardRootModule.handleSearch();
            });

        })
        .catch(() => {
          this.isPageShow = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
};
</script>
<style lang="scss">
@import "./css/common.scss";
</style>
<style lang="scss">
.share-code-dialog {
  @media screen and (max-width: 600px) {

    .el-dialog {
      width: 90% !important;
    }
  }
  .el-dialog {
    width: 550px;
    padding-top: 0;
    border-radius: 8px 8px 0px 0px;
    height: 275px;
    display: flex;
    flex-direction: column;
  }
  .el-dialog__header {
    display: flex;
    width: 100%;
    border-radius: 8px 8px 0px 0px;
    height: 80px;
    background: #3d82ea;
    position: relative;
    opacity: 1;
  }
  .el-dialog__title {
    height: 80px;
    font-size: 16px;
  }
  .el-dialog__body {
    flex: 1;
    padding-bottom: 16px;
    overflow: hidden;
    padding-left: 48px;
    padding-right: 48px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
</style>
